<template>
  <el-form :model="ruleForm" :rules="rules" label-width="150px" ref="ruleFormRef">
    <!-- 基本信息 -->
    <div class="bg-white mt-[10px]">
      <BaseHead>基本信息</BaseHead>
      <div class="p-[10px]">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="成果名称" prop="name">
              <el-input placeholder="请输入成果名称" v-model="ruleForm.name" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属单位" prop="unitId">
              <el-select v-model="ruleForm.unitId" :disabled="Cookies.get('role-key') == 'biz_kyry'"
                placeholder="请选择所属单位" clearable>
                <el-option v-for="item in zcgsdwList" :key="item.codeColumn" :label="item.valueColumn"
                  :value="item.codeColumn" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成果联系人" prop="txAuthorName">
              <el-select v-model="ruleForm.txAuthorName" filterable remote reserve-keyword placeholder="请输入关键字检索"
                :remote-method="remoteMethod" @change="selectAuthor1" :loading="loading">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"
                  @click="changeTxAuthorSelect(item)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人电话" prop="txAuthorTel">
              <el-input placeholder="请输入联系人电话" v-model="ruleForm.txAuthorTel" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="第一完成人" prop="firstAuthorName">
              <el-select v-model="ruleForm.firstAuthorName" :disabled="Cookies.get('role-key') == 'biz_kyry'" filterable
                remote reserve-keyword placeholder="请输入关键字检索" :remote-method="remoteMethod" @change="selectAuthor"
                :loading="loading">
                <el-option v-for="item in options" @click="changeFirstAuthorSelect(item)" :key="item.value"
                  :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="完成人电话" prop="authorTel">
              <el-input placeholder="请输入完成人电话" v-model="ruleForm.authorTel" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="研发起止时间">
              <el-date-picker v-model="ruleForm.researchDate" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                type="daterange" range-separator="至" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="知识产权类型" prop="typeId">
              <el-checkbox-group v-model="ruleForm.typeId">
                <el-checkbox v-for="item in typeIdList" :label="item.code" :key="item.code">{{
    item.name
  }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="知识产权编号" prop="code">
              <el-input placeholder="知识产权编号" v-model="ruleForm.code" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="成果体现形式" prop="manifestationId">
              <el-checkbox-group v-model="ruleForm.manifestationId">
                <el-checkbox :value="item.code" size="large" v-for="item in manifestationIdList" :key="item.code">
                  {{ item.name }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="技术成熟度" prop="matureId">
              <el-checkbox-group v-model="ruleForm.matureId">
                <el-checkbox :value="item.code" size="large" v-for="item in matureIdList" :key="item.code">
                  {{ item.name }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="技术先进度" prop="advancedId">
              <el-checkbox-group v-model="ruleForm.advancedId">
                <el-checkbox :value="item.code" size="large" v-for="item in advancedIdList" :key="item.code">
                  {{ item.name }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所属高新技术领域" prop="domainId">
              <el-checkbox-group v-model="ruleForm.domainId">
                <el-checkbox :value="item.code" size="large" v-for="item in domainIdList" :key="item.code">
                  {{ item.name }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="成果主要应用行业" prop="industryId">
              <el-checkbox-group v-model="ruleForm.industryId">
                <el-checkbox :value="item.id" size="large" v-for="item in sshyList" :key="item.id">
                  {{ item.label }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="成果主要应用行业" prop="industryId">
              <el-select v-model="ruleForm.industryId" placeholder="请选择所属行业" clearable>
                <el-option
                  v-for="item in sshyList"
                  :key="item.codeColumn"
                  :label="item.valueColumn"
                  :value="item.codeColumn"
                />
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="成果获得方式" prop="obtainId">
              <el-checkbox-group v-model="ruleForm.obtainId">
                <el-checkbox :value="item.code" size="large" v-for="item in obtainIdList" :key="item.code">
                  {{ item.name }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="获得政府支持情况" prop="support.check">
              <el-checkbox-group v-model="ruleForm.support.check">
                <el-checkbox :value="item.code" size="large" v-for="item in supportIdList" :key="item.code">
                  {{ item.name }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="custom-el-col">
            <el-form-item label="计划/专项类别">
              <el-input v-model="ruleForm.support.type" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8" class="custom-el-col">
            <el-form-item label="获得经费(元)">
              <el-input v-model="ruleForm.support.fee" @input="validateNumber" type="number" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8" class="custom-el-col">
            <el-form-item label="自筹资金(元)">
              <el-input v-model="ruleForm.support.zczj" @input="validateNumber1" type="number" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8" class="custom-el-col">
            <el-form-item label="自筹资金来源">
              <el-input v-model="ruleForm.support.zczj_source" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="成果简介" prop="introduce">
              <el-input v-model="ruleForm.introduce" type="textarea" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="成果附件">
              <FileUpload :uploadUrl="uploadUrl" :limit="1" tip="支持图片、视频、文本,每个附件大小不超过20M" v-model="fileList"
                @change="fileChange">
              </FileUpload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所需支持或建议">
              <el-input v-model="ruleForm.suggestion" type="textarea" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="拟采取转化方式" prop="transforId">
              <el-checkbox-group v-model="ruleForm.transforId">
                <el-checkbox :value="item.code" size="large" v-for="item in transforIdList" :key="item.code">
                  {{ item.name }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="ruleForm.note" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </div>
  </el-form>
</template>

<script setup>
import BaseHead from '@/views/project/components/BaseHead.vue'
import { getPersonDetails } from '@/api/achievement/common.js'
import { getCategory } from '@/api/system/category'
import { getkycgzhAdd, getkycgzhUpdate } from '@/api/achievement/zscq'
import FileUpload from '@/views/achievement/components/FileUpload.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Cookies from 'js-cookie'
import cloneDeep from 'lodash/cloneDeep';

const props = defineProps({
  zcgsdwList: Array,
  typeIdList: Array,
  manifestationIdList: Array,
  matureIdList: Array,
  advancedIdList: Array,
  domainIdList: Array,
  sshyList: Array,
  obtainIdList: Array,
  supportIdList: Array,
  transforIdList: Array,
})
const defaultProps = {
  children: 'children',
  label: 'label',
}

const ruleForm = reactive({
  name: '',
  code: '',
  txAuthorName: '',
  txAuthorTel: '',
  authorTel: '',
  unitId: '',
  typeId: [],
  researchDate: '',
  manifestationId: [],
  matureId: [],
  advancedId: [],
  domainId: [],
  industryId: [],
  obtainId: [],
  support: {
    check: [],
    type: '',
    fee: '',
    zczj: '',
    zczj_source: '',
  },
  introduce: [],
  suggestion: '',
  transforId: [],
  note: '',
  fileIds: '',
})
const rules = ref({
  name: [{ required: true, message: '请输入成果名称', trigger: 'blur' }],
  unitId: [
    {
      required: true,
      message: '请选择所属单位',
      trigger: 'change',
    },
  ],
  txAuthorName: [{ required: true, message: '请选择成果联系人', trigger: 'change' }],
  txAuthorTel: [{ required: true, message: '请输入联系人电话', trigger: 'blur' }],
  firstAuthorName: [{ required: true, message: '请选择第一完成人', trigger: 'change' }],
  authorTel: [{ required: true, message: '请输入完成人电话', trigger: 'blur' }],
  typeId: [{ required: true, message: '请选择知识产权类型', trigger: 'change' }],
  manifestationId: [
    {
      required: true,
      message: '请选择成果体现形式',
      trigger: 'change',
    },
  ],
  matureId: [
    {
      required: true,
      message: '请选择技术成熟度',
      trigger: 'change',
    },
  ],
  advancedId: [
    {
      required: true,
      message: '请选择技术先进度',
      trigger: 'change',
    },
  ],
  domainId: [
    {
      required: true,
      message: '请选择所属高新技术领域',
      trigger: 'change',
    },
  ],
  industryId: [
    {
      required: true,
      message: '请选择成果主要应用行业',
      trigger: 'change',
    },
  ],
  obtainId: [
    {
      required: true,
      message: '请选择成果获得方式',
      trigger: 'change',
    },
  ],
  'support.check': [
    {
      required: true,
      message: '请选择获得政府支持情况',
      trigger: 'change',
    },
  ],
  introduce: [{ required: true, message: '请输入成果简介', trigger: 'blur' }],
  transforId: [
    {
      required: true,
      message: '请选择拟采取转化方式',
      trigger: 'change',
    },
  ],
})
const options = ref([])
const loading = ref(false)
const remoteMethod = (query) => {
  if (query) {
    loading.value = true
    let pamrs = {
      name: query,
    }
    getPersonDetails(pamrs).then((res) => {
      console.log(res, 'res')
      if (res.code == 200) {
        let arr = res.data
        arr.map((item) => {
          item.value = item.name + ' ' + item.account + ' ' + item.unitName;
          item.label = item.name + ' ' + item.account + ' ' + item.unitName;
        })
        options.value = arr
        loading.value = false
      }
    })
  } else {
    options.value = []
  }
}
const changeFirstAuthorSelect = (value) => {
  console.log(value, 'value')
  ruleForm.firstAuthorId = value.id
  ruleForm.firstAuthorAccount = value.account
  ruleForm.firstAuthorTitleId = value.titleId
  ruleForm.firstAuthorSexid = value.sexId
  ruleForm.firstAuthorEduLevelId = value.eduLevelId
  ruleForm.firstAuthorEduDegreeId = value.eduDegreeId
  // ruleForm.firstAuthorName = value.name
}

const selectAuthor = (e, index, row) => {
  let userInfo = options.value.find(item => item.value == e)
  ruleForm.firstAuthorName = userInfo.name
  ruleForm.authorTel = userInfo.mobile
}
const selectAuthor1 = (e, index, row) => {
  let userInfo = options.value.find(item => item.value == e)
  ruleForm.txAuthorName = userInfo.name
  ruleForm.txAuthorTel = userInfo.mobile
}

const changeTxAuthorSelect = (value) => {
  console.log(value, 'value')
  let txAuthor = {
    id: value.id,
    name: value.name,
    account: value.account,
  }
  ruleForm.txAuthor = JSON.stringify(txAuthor)
}
const ruleFormRef = ref()
const emit = defineEmits(['closeDiglog', 'endLoading', 'startLoading'])
const submitForm = async (i) => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      let params = cloneDeep(ruleForm)
      console.log(params, 'params')

      params.submitType = i
      params.researchStartdate = params.researchDate[0]
      params.researchEnddate = params.researchDate[1]
      params.typeId = params.typeId.join(',')
      params.manifestationId = params.manifestationId.join(',')
      params.matureId = params.matureId.join(',')
      params.advancedId = params.advancedId.join(',')
      params.domainId = params.domainId.join(',')
      params.industryId = params.industryId.join(',')
      params.obtainId = params.obtainId.join(',')
      params.support.check = params.support.check.join(',')
      params.supportId = JSON.stringify(params.support)
      params.transforId = params.transforId.join(',')
      console.log(params, 'params')
      emit('startLoading', "")
      if (params.id) {
        getkycgzhUpdate(params).then((res) => {
          if (res.code == 200) {
            ElMessage({
              message: res.msg,
              type: 'success',
            })
            emit('closeDiglog', '')
          } else {
            ElMessage({
              message: res.msg,
              type: 'error',
            })
          }
          emit('endLoading', "")
        })
      } else {
        getkycgzhAdd(params).then((res) => {
          if (res.code == 200) {
            ElMessage({
              message: res.msg,
              type: 'success',
            })
            emit('closeDiglog', '')
          } else {
            ElMessage({
              message: res.msg,
              type: 'error',
            })
          }
          emit('endLoading', "")
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
const uploadUrl = `/commonFile/uploadFile?modelName=productTransform`
const fileList = ref([])

const getRuleForm = (i) => {
  console.log(i, 'info')
  for (const key in i) {
    ruleForm[key] = i[key]
  }
  if (i.fileList && i.fileList.length > 0) {
    fileList.value = i.fileList.map((item) => {
      return {
        name: item.fileName,
        id: item.id,
      }
    })
  }
  ruleForm.researchDate = [ruleForm.researchStartdate, ruleForm.researchEnddate]
  ruleForm.typeId = ruleForm.typeId.split(',')
  ruleForm.manifestationId = ruleForm.manifestationId.split(',')
  ruleForm.matureId = ruleForm.matureId.split(',')
  ruleForm.advancedId = ruleForm.advancedId.split(',')
  ruleForm.domainId = ruleForm.domainId.split(',')
  ruleForm.industryId = ruleForm.industryId.split(',')
  ruleForm.obtainId = ruleForm.obtainId.split(',')
  ruleForm.transforId = ruleForm.transforId.split(',')
  ruleForm.support = JSON.parse(ruleForm.supportId)
  ruleForm.support.check = ruleForm.support.check.split(',')
  ruleForm.txAuthorName = JSON.parse(ruleForm.txAuthor).name
  console.log(ruleForm, 'ruleForm')
}
//上传的文件改变
const fileChange = () => {
  const ids = fileList.value.map((item) => {
    const id = item.response ? item.response.data : item.id
    return id
  })
  ruleForm.fileIds = ids.join(',')
}

const getKyryInfo = (i) => {
  if (i.unitId) {
    ruleForm.unitId = i.unitId
  }
  if (i.name) {
    ruleForm.firstAuthorName = i.name
  }
  if (i.mobile) {
    ruleForm.authorTel = i.mobile
  }


  if (i.id) {
    ruleForm.firstAuthorId = i.id
  }
  if (i.account) {
    ruleForm.firstAuthorAccount = i.account
  }
  if (i.titleId) {
    ruleForm.firstAuthorTitleId = i.titleId
  }
  if (i.sexId) {
    ruleForm.firstAuthorSexid = i.sexId
  }
  if (i.eduLevelId) {
    ruleForm.firstAuthorEduLevelId = i.eduLevelId
  }
  if (i.eduDegreeId) {
    ruleForm.firstAuthorEduDegreeId = i.eduDegreeId
  }
}

const validateNumber = (value) => {
  const minValue = 0; // 定义最小值
  if (value < minValue) {
    ruleForm.support.fee = minValue; // 或者设置为空字符串或上一个有效值
  }
  // 使用正则表达式限制小数点后最多4位
  ruleForm.support.fee = value.toString().replace(/[^0-9.]/g, '').replace(/(\.\d{2})\d*/g, '$1');
};

const validateNumber1 = (value) => {
  const minValue = 0; // 定义最小值
  if (value < minValue) {
    ruleForm.support.zczj = minValue; // 或者设置为空字符串或上一个有效值
  }
  // 使用正则表达式限制小数点后最多4位
  ruleForm.support.zczj = value.toString().replace(/[^0-9.]/g, '').replace(/(\.\d{2})\d*/g, '$1');
};




// 把数据暴露出去供父组件调用
defineExpose({
  submitForm,
  getRuleForm,
  getKyryInfo
})
</script>

<style scoped lang="scss">
@import url('@/views/achievement/index.scss');

.custom-el-col {
  padding-right: 0px !important;
  padding-left: 0px !important;
}
</style>
